#include <QTimer>
#include "agenttaskdatathreshtrigger.h"
#include "Agent/agentprotocol.h"
#include "macro.h"

AgentTaskDataThreshTrigger::AgentTaskDataThreshTrigger
(QMap <QByteArray,QByteArray> mapIPPortReqPacket,QByteArray packet, QString paramAppIP, quint16 paramAppPort, QObject *parent)
    :AgentTaskBase(mapIPPortReqPacket,packet,paramAppIP,paramAppPort,parent)
{

}
void AgentTaskDataThreshTrigger::slotInitDerivedClass()
{

    if(fieldSrcNodeName.isEmpty()||fieldSrcSensorName.isEmpty())
    {
        emit sigSendDataToApp(agentProtocol->replyLineBadRequest()+"\n\n"
            "SourceNodeName or SourceSensorName is missing!",appIP,appPort);
        deleteLater();
        return;
    }

    holdTimesDone=0;
    baPacketToGetData="Get "+fieldSrcNodeName+"/RealTimeData/query?SensorName="
            +fieldSrcSensorName;
    slotSendPacket(baPacketToGetData,aServerIP,aServerPort);

    timerForGetData=new QTimer(this);
    connect(timerForGetData,SIGNAL(timeout()),this,SLOT(slotGetData()));
    timerForGetData->start(fieldTimeOutSeconds*1000);

    isCreatedSuccessfully=true;

}
void AgentTaskDataThreshTrigger::analyzeIncomeDatagram(QByteArray packet)
{
    QByteArray packetUpper=packet.simplified().toUpper();
    if(packetUpper.startsWith("ERR"))
    {
        emit sigSendDataToApp(agentProtocol->replyLineBadRequest()+"\n\n"+
            packet,appIP,appPort);
        deleteLater();
        return;
    }
    else if(packetUpper.startsWith("DATA"))
    {
        QList <QByteArray> listFieldsInData=packet.trimmed().split('\n');

        if(listFieldsInData.size()<2)
            return;
        else
        {
            QByteArray dataLine=listFieldsInData.at(1);
            QList <QByteArray> listFieldsInOneLine=dataLine.split('\t');
            if(listFieldsInOneLine.size()<3)
                return;
            else if(listFieldsInOneLine.at(1).toUpper()!=fieldSrcSensorName.toUpper())
                return;
            else if(isComparisonHit(listFieldsInOneLine.at(2)))
            {
                holdTimesDone++;
                if(holdTimesDone>=fieldHoldTimes)
                {
                    emit sigSetIPAnalyzeIncomeDatagram(fieldPayLoad,QHostAddress(appIP),appPort);
                    holdTimesDone=0;
                }
            }
            else
                holdTimesDone=0;
        }

    }
}

void AgentTaskDataThreshTrigger::slotGetData()
{
    slotSendPacket(baPacketToGetData,aServerIP,aServerPort); //发送请求数据
}

AgentTaskDataThreshTrigger::~AgentTaskDataThreshTrigger()
{

}


